package org.jzs.mybaseapp.section.home;

import android.app.Dialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.filter.Filter;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import org.jzs.mybaseapp.MyApplaciton;
import org.jzs.mybaseapp.R;
import org.jzs.mybaseapp.common.utils.AppLog;
import org.jzs.mybaseapp.common.utils.ImageUtil;
import org.jzs.mybaseapp.common.utils.MediaScannerUtils;
import org.jzs.mybaseapp.common.utils.PermissionUtils;
import org.jzs.mybaseapp.common.widget.GifSizeFilter;
import org.jzs.mybaseapp.common.widget.photoinfodialog.PhotoDialog;
import org.jzs.mybaseapp.section.home.entity.PhotoEntity;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;

/**
 * @author Jzs created 2017/8/2
 */

public class PhotoActivity extends AppCompatActivity {

    private ImageView mSourImage;
    private ImageView mWartermarkImage;
    List<Uri> mSelected;
    private Bitmap textBitmap;
    private PhotoDialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_photo);
        ButterKnife.bind(this);
        AppLog.e(MyApplaciton.getInstance().getCacheDir() + "");
        initView();
    }

    private void initView() {
        mSourImage = (ImageView) findViewById(R.id.sour_pic);
        mWartermarkImage = (ImageView) findViewById(R.id.wartermark_pic);


        Bitmap sourBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.sour_pic);
        mSourImage.setImageBitmap(sourBitmap);

//        Bitmap waterBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.weixin);

//        Bitmap watermarkBitmap = ImageUtil.createWaterMaskCenter(sourBitmap, waterBitmap);
//        watermarkBitmap = ImageUtil.createWaterMaskLeftBottom(this, watermarkBitmap, waterBitmap, 0, 0);
//        watermarkBitmap = ImageUtil.createWaterMaskRightBottom(this, watermarkBitmap, waterBitmap, 0, 0);
//        watermarkBitmap = ImageUtil.createWaterMaskLeftTop(this, watermarkBitmap, waterBitmap, 0, 0);
//        watermarkBitmap = ImageUtil.createWaterMaskRightTop(this, watermarkBitmap, waterBitmap, 0, 0);

        Bitmap textBitmap = ImageUtil.drawTextToLeftTop(this, sourBitmap, "左上角", 16, Color.RED, 0, 0);
        textBitmap = ImageUtil.drawTextToRightBottom(this, textBitmap, "右下角", 16, Color.RED, 0, 0);
        textBitmap = ImageUtil.drawTextToRightTop(this, textBitmap, "右上角", 16, Color.RED, 0, 0);
        textBitmap = ImageUtil.drawTextToLeftBottom(this, textBitmap, "左下角", 16, Color.RED, 0, 0);
        textBitmap = ImageUtil.drawTextToCenter(this, textBitmap, "中间", 16, Color.RED);

        mWartermarkImage.setImageBitmap(textBitmap);

        dialog = new PhotoDialog();
        dialog.initDialog(this);
        dialog.setCallBack(new PhotoDialog.DialogCallBack() {
            @Override
            public void sure() {
                mList = dialog.getList();
            }

            @Override
            public void cancel() {

            }
        });
    }

    private List<PhotoEntity> mList = new ArrayList<>();

    public void set(View v) {
        dialog.show();
    }

    public void open(View v) {
        PermissionUtils.getInstance().requestCameraAndStorage(this);
    }

    public void save(View v) {
        String fileName = System.currentTimeMillis() + "";
        String picPath = MediaStore.Images.Media.insertImage(getContentResolver(), textBitmap, fileName, "description");
        MediaScannerUtils.mediaScan(this, picPath);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        AndPermission.onRequestPermissionsResult(requestCode, permissions, grantResults, listener);
    }

    private PermissionListener listener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, List<String> grantedPermissions) {
            // 权限申请成功回调。
            if (requestCode == PermissionUtils.REQUEST_CODE_PERMISSION_CAMERA_STORAGE) {
                // TODO 相应代码。
                Matisse.from(PhotoActivity.this)
                        .choose(MimeType.allOf())
                        .countable(true)
                        .maxSelectable(1)
                        .addFilter(new GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
                        .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                        .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                        .thumbnailScale(0.85f)
                        .capture(true)
                        .captureStrategy(
                                new CaptureStrategy(true, "com.szt.myapplicationee.fileprovider"))
                        .imageEngine(new GlideEngine())
                        .forResult(100);
            }
        }

        @Override
        public void onFailed(int requestCode, List<String> deniedPermissions) {
            // 权限申请失败回调。
            switch (requestCode) {
                case PermissionUtils.REQUEST_CODE_PERMISSION_CAMERA_STORAGE:
                    //弹出提示框
                    AndPermission.defaultSettingDialog(PhotoActivity.this, PermissionUtils.REQUEST_CODE_PERMISSION_CAMERA_STORAGE).show();
                    break;

                default:

                    break;
            }
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100 && resultCode == RESULT_OK) {
            mSelected = Matisse.obtainResult(data);
            Uri uri = mSelected.get(0);
            Glide.with(PhotoActivity.this).load(uri).override(600, 600).into(mSourImage);
//            mSourImage.setImageURI(uri);
            try {
                Bitmap bitmapFormUri = ImageUtil.getBitmapFormUri(this, uri, false);
                textBitmap = ImageUtil.drawProjectText(this, bitmapFormUri, mList, 16, Color.RED, 0, 0);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                textBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
                byte[] bytes = baos.toByteArray();

                Glide.with(PhotoActivity.this).load(bytes).override(600, 600).into(mWartermarkImage);
            } catch (IOException e) {
                e.printStackTrace();
            }


            Log.d("Matisse", "mSelected: " + mSelected);
        }
    }
}
